package com.yaoweigroup.community.ui.home;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Html;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.adapter.HomeGridAdapter;
import com.yaoweigroup.community.adapter.MainFocusAdapter;
import com.yaoweigroup.community.config.Constant;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.db.DBUtil;
import com.yaoweigroup.community.enity.Adv;
import com.yaoweigroup.community.enity.HomeIcon;
import com.yaoweigroup.community.enity.RecommendShop;
import com.yaoweigroup.community.ui.shop.HomeShopListActivity;
import com.yaoweigroup.community.ui.shop.ShopDetailActivity;
import com.yaoweigroup.community.util.BitmapHelp;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.UtilHttp;

/**
 * 主页 --详细页面
 * 
 * @author xi
 * 
 */
public class MainHomeActivity extends Activity implements OnPageChangeListener,
		OnClickListener {

	private ViewPager viewpager;
	private LinearLayout viewGroup;
	private MainFocusAdapter pagerAdapter;
	private ImageView[] imageViews;

	private GridView gridView;
	private HomeGridAdapter gridAdapter;
	private List<HomeIcon> items;
	private Intent intent;
	private Context context;
	private DBUtil dbUtil;
	private ObjectMapper mapper;
	private List<Adv> advs;

	private ProgressBar progress;
	private LinearLayout recommend_ll;
	private ProgressBar re_progress;
	private BitmapUtils bitmapUtils;
	private BitmapDisplayConfig bigPicDisplayConfig;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_home);
		context = this;
		bitmapUtils = BitmapHelp.getBitmapUtils(context);
		bigPicDisplayConfig = new BitmapDisplayConfig();
		bigPicDisplayConfig.setLoadFailedDrawable(context.getResources()
				.getDrawable(R.drawable.bucket_no_picture));
		bigPicDisplayConfig.setLoadingDrawable(context.getResources()
				.getDrawable(R.drawable.bucket_no_picture));
		dbUtil = DBUtil.newInstance(this);
		mapper = new ObjectMapper();
		initRes();
		obtainAdv();
		obtainRecommend();
	}

	@Override
	public void onResume() {
		LogUtil.d("wxf", "home is resume");
		initData();
		super.onResume();

	}

	private void initData() {
		items = new ArrayList<HomeIcon>();
		gridAdapter = new HomeGridAdapter(this, items);
		try {
			List<HomeIcon> list = dbUtil.db.findAll(HomeIcon.class);
			if (list != null && list.size() > 0) {
				if (list.size() == 9) {
					gridAdapter.setDataChange(list);
				} else {
					HomeIcon gjhc = new HomeIcon();
					gjhc.setResId(R.drawable.add_icon);
					gjhc.setClassName("com.yaoweigroup.community.ui.home.AppsActivity");
					gjhc.setTypeName("添加");
					list.add(gjhc);
					gridAdapter.setDataChange(list);
				}

			} else {
				items.addAll(Constant.defaultHomeList);
				dbUtil.db.saveOrUpdateAll(Constant.defaultHomeList);
				HomeIcon gjhc = new HomeIcon();
				gjhc.setResId(R.drawable.add_icon);
				gjhc.setClassName("com.yaoweigroup.community.ui.home.AppsActivity");
				gjhc.setTypeName("添加");
				items.add(gjhc);
				gridAdapter.setDataChange(items);
			}
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		gridView.setAdapter(gridAdapter);

	}

	// private ImageView left_icon_1;
	// private TextView left_name_1;
	// private TextView left_des_1;
	// private TextView mid_name_1;
	// private TextView mid_des_1;
	// private ImageView mid_icon_1;
	// private TextView mid_name_2;
	// private TextView mid_des_2;
	// private ImageView mid_icon_2;
	//
	// private TextView right_name_1;
	// private TextView right_des_1;
	// private ImageView right_icon_1;
	// private TextView right_name_2;
	// private TextView right_des_2;
	// private ImageView right_icon_2;
	//
	// private TextView bottom_name_1;
	// private TextView bottom_des_1;
	// private ImageView bottom_icon_1;
	// private TextView bottom_name_2;
	// private TextView bottom_des_2;
	// private ImageView bottom_icon_2;
	//
	// private LinearLayout left_ll;
	// private LinearLayout mid_1_ll;
	// private LinearLayout mid_2_ll;
	// private LinearLayout right_1_ll;
	// private LinearLayout right_2_ll;

	private ImageView iv_1;
	private ImageView iv_2;
	private ImageView iv_3;
	private ImageView iv_4;
	private String id = "";

	private void initRes() {

		iv_1 = (ImageView) findViewById(R.id.iv_1);
		iv_1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainHomeActivity.this,
						HomeShopListActivity.class);
				intent.putExtra("id", 1);
				startActivity(intent);
			}
		});
		iv_2 = (ImageView) findViewById(R.id.iv_2);
		iv_2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainHomeActivity.this,
						HomeShopListActivity.class);

				intent.putExtra("id", 2);
				startActivity(intent);
			}
		});
		iv_3 = (ImageView) findViewById(R.id.iv_3);
		iv_3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainHomeActivity.this,
						HomeShopListActivity.class);
				intent.putExtra("id", 3);
				startActivity(intent);
			}
		});
		iv_4 = (ImageView) findViewById(R.id.iv_4);
		iv_4.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainHomeActivity.this,
						HomeShopListActivity.class);

				intent.putExtra("id", 4);
				startActivity(intent);
			}
		});
		// left_ll = (LinearLayout) findViewById(R.id.left_ll);
		// left_ll.setOnClickListener(this);
		// mid_1_ll = (LinearLayout) findViewById(R.id.mid_1_ll);
		// mid_1_ll.setOnClickListener(this);
		// mid_2_ll = (LinearLayout) findViewById(R.id.mid_2_ll);
		// mid_2_ll.setOnClickListener(this);
		// right_1_ll = (LinearLayout) findViewById(R.id.right_1_ll);
		// right_1_ll.setOnClickListener(this);
		// right_2_ll = (LinearLayout) findViewById(R.id.right_2_ll);
		// right_2_ll.setOnClickListener(this);

		progress = (ProgressBar) findViewById(R.id.progress);
		gridView = (GridView) findViewById(R.id.gridView);
		initData();

		viewpager = (ViewPager) findViewById(R.id.viewpager);
		viewGroup = (LinearLayout) findViewById(R.id.viewGroup);

		advs = new ArrayList<Adv>();
		pagerAdapter = new MainFocusAdapter(advs, this);
		viewpager.setAdapter(pagerAdapter);
		viewpager.setOnPageChangeListener(this);
		viewpager.setCurrentItem(0);

		re_progress = (ProgressBar) findViewById(R.id.re_progress);
		recommend_ll = (LinearLayout) findViewById(R.id.recommend_ll);

		// left_icon_1 = (ImageView) findViewById(R.id.left_icon_1);
		// left_name_1 = (TextView) findViewById(R.id.left_name_1);
		// left_des_1 = (TextView) findViewById(R.id.left_des_1);
		// mid_name_1 = (TextView) findViewById(R.id.mid_name_1);
		// mid_des_1 = (TextView) findViewById(R.id.mid_des_1);
		// mid_icon_1 = (ImageView) findViewById(R.id.mid_icon_1);
		// mid_name_2 = (TextView) findViewById(R.id.mid_name_2);
		// mid_des_2 = (TextView) findViewById(R.id.mid_des_2);
		// mid_icon_2 = (ImageView) findViewById(R.id.mid_icon_2);
		//
		// right_name_1 = (TextView) findViewById(R.id.right_name_1);
		// right_des_1 = (TextView) findViewById(R.id.right_des_1);
		// right_icon_1 = (ImageView) findViewById(R.id.right_icon_1);
		// right_name_2 = (TextView) findViewById(R.id.right_name_2);
		// right_des_2 = (TextView) findViewById(R.id.right_des_2);
		// right_icon_2 = (ImageView) findViewById(R.id.right_icon_2);

	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int position) {
		setImageBackground(position);
	}

	private void setImageBackground(int selectItems) {
		for (int i = 0; i < imageViews.length; i++) {
			if (i == selectItems) {
				imageViews[i].setBackgroundResource(R.drawable.new_focus_icon);
			} else {
				imageViews[i]
						.setBackgroundResource(R.drawable.new_unfocus_icon);
			}
		}
	}

	private void obtainAdv() {
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("typename", "APPHome");
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.advertisement, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							String data = obj.getString("data");
							advs = mapper.readValue(data,
									new TypeReference<List<Adv>>() {
									});
							if (state == 200) {
								handler.sendEmptyMessage(DATA_SUCCESS);
							} else {
								handler.sendEmptyMessage(DATA_FAIL);
							}

						} catch (Exception e) {
							handler.sendEmptyMessage(DATA_FAIL);
							LogUtil.e("wxf", e.toString());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(DATA_FAIL);

					}

				});
	}

	private List<RecommendShop> recommends;

	private void obtainRecommend() {
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.getRecommendProducts,
				params, new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 200) {
								recommends = mapper.readValue(
										obj.getString("data"),
										new TypeReference<List<RecommendShop>>() {
										});
								handler.sendEmptyMessage(RECOMMEND_SUCCESS);
							} else {
								handler.sendEmptyMessage(RECOMMEND_FAIL);
							}
						} catch (Exception e) {
							LogUtil.e("wxf", e.toString());
							handler.sendEmptyMessage(RECOMMEND_FAIL);

						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(RECOMMEND_FAIL);
					}

				});
	}

	public final int DATA_SUCCESS = 0x2210;
	public final int DATA_FAIL = DATA_SUCCESS + 1;
	public final int RECOMMEND_SUCCESS = DATA_SUCCESS + 2;
	public final int RECOMMEND_FAIL = DATA_SUCCESS + 3;
	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case DATA_SUCCESS:
				progress.setVisibility(View.GONE);
				if (advs != null && advs.size() > 0) {
					imageViews = new ImageView[advs.size()];
					for (int i = 0; i < advs.size(); i++) {
						LinearLayout.LayoutParams parmas = new LinearLayout.LayoutParams(
								12, 12);
						parmas.leftMargin = 5;
						parmas.rightMargin = 5;
						ImageView imageView = new ImageView(
								MainHomeActivity.this);
						imageView.setLayoutParams(parmas);
						imageViews[i] = imageView;
						if (i == 0) {
							imageView
									.setBackgroundResource(R.drawable.new_focus_icon);
						} else {
							imageView
									.setBackgroundResource(R.drawable.new_unfocus_icon);
						}
						viewGroup.addView(imageView);
					}
					pagerAdapter.setDataChange(advs);
				}
				break;
			case DATA_FAIL:
				progress.setVisibility(View.GONE);
				break;
			case RECOMMEND_FAIL:
				recommend_ll.setVisibility(View.GONE);
				re_progress.setVisibility(View.GONE);
				break;
			case RECOMMEND_SUCCESS:
				// re_progress.setVisibility(View.GONE);
				// recommend_ll.setVisibility(View.VISIBLE);
				// if (recommends != null && recommends.size() > 0) {
				// updateData();
				// }
				break;
			}
		};
	};

	private void updateData() {
		//
		try {
			// bitmapUtils.display(left_icon_1, recommends.get(0).getHeadimg(),
			// bigPicDisplayConfig);
			//
			// String name0 = recommends.get(0).getName();
			// if (name0.length() > 6) {
			// name0 = name0.substring(0, 6) + "..";
			// }
			// left_name_1.setText(name0);
			// String des0 = recommends.get(0).getDes();
			// des0 = fiterHtmlTag(des0, "img");
			// if (des0.length() > 15) {
			// des0 = des0.substring(0, 15) + "..";
			// }
			// left_des_1.setText(Html.fromHtml(des0));
			// String name2 = recommends.get(2).getName();
			// if (name2.length() > 6) {
			// name2 = name2.substring(0, 6) + "..";
			// }
			// mid_name_1.setText(name2);
			// String des1 = recommends.get(1).getDes();
			// des1 = fiterHtmlTag(des1, "img");
			// if (des1.length() > 15) {
			// des1 = des1.substring(0, 15) + "..";
			// }
			// mid_des_1.setText(Html.fromHtml(des1));
			// bitmapUtils.display(iv_1, recommends.get(0).getHeadimg(),
			// bigPicDisplayConfig);
			// bitmapUtils.display(iv_2, recommends.get(1).getHeadimg(),
			// bigPicDisplayConfig);
			// bitmapUtils.display(iv_3, recommends.get(2).getHeadimg(),
			// bigPicDisplayConfig);
			// bitmapUtils.display(iv_4, recommends.get(3).getHeadimg(),
			// bigPicDisplayConfig);
			//
			// String name3 = recommends.get(2).getName();
			// if (name3.length() > 6) {
			// name3 = name3.substring(0, 6) + "..";
			// }
			// mid_name_2.setText(name3);
			// String des2 = recommends.get(2).getDes();
			// des2 = fiterHtmlTag(des2, "img");
			// if (des2.length() > 15) {
			// des2 = des2.substring(0, 15) + "..";
			// }
			// mid_des_2.setText(Html.fromHtml(des2));
			// bitmapUtils.display(mid_icon_2, recommends.get(2).getHeadimg(),
			// bigPicDisplayConfig);
			//
			// String name4 = recommends.get(3).getName();
			// if (name4.length() > 6) {
			// name4 = name4.substring(0, 6) + "..";
			// }
			// right_name_1.setText(name4);
			// String des3 = recommends.get(3).getDes();
			// des3 = fiterHtmlTag(des3, "img");
			// if (des3.length() > 15) {
			// des3 = des3.substring(0, 15) + "..";
			// }
			// right_des_1.setText(Html.fromHtml(des3));
			// bitmapUtils.display(right_icon_1, recommends.get(3).getHeadimg(),
			// bigPicDisplayConfig);
			//
			// String name5 = recommends.get(4).getName();
			// if (name5.length() > 6) {
			// name5 = name5.substring(0, 6) + "..";
			// }
			// right_name_2.setText(name5);
			// String des4 = recommends.get(4).getDes();
			// des4 = fiterHtmlTag(des4, "img");
			// if (des4.length() > 15) {
			// des4 = des4.substring(0, 15) + "..";
			// }
			// right_des_2.setText(Html.fromHtml(des4));
			// bitmapUtils.display(right_icon_2, recommends.get(4).getHeadimg(),
			// bigPicDisplayConfig);
			//
			// String name6 = recommends.get(5).getName();
			// if (name6.length() > 6) {
			// name6 = name6.substring(0, 6) + "..";
			// }
			// bottom_name_1.setText(name6);
			// String des5 = recommends.get(5).getDes();
			// des5 = fiterHtmlTag(des5, "img");
			// if (des5.length() > 15) {
			// des5 = des5.substring(0, 15) + "..";
			// }
			// bottom_des_1.setText(Html.fromHtml(des5));
			// bitmapUtils.display(bottom_icon_1,
			// recommends.get(5).getHeadimg(),
			// bigPicDisplayConfig);
			//
			// String name7 = recommends.get(6).getName();
			// if (name7.length() > 6) {
			// name7 = name7.substring(0, 6) + "..";
			// }
			// bottom_name_2.setText(name7);
			// String des6 = recommends.get(6).getDes();
			// des6 = fiterHtmlTag(des6, "img");
			// if (des6.length() > 15) {
			// des6 = des6.substring(0, 15) + "..";
			// }
			// bottom_des_2.setText(Html.fromHtml(des6));
			// bitmapUtils.display(bottom_icon_2,
			// recommends.get(6).getHeadimg(),
			// bigPicDisplayConfig);
		} catch (Exception e) {

		}
	}

	public String fiterHtmlTag(String str, String tag) {
		String regxp = "<\\s*" + tag + "\\s+([^>]*)\\s*>";
		Pattern pattern = Pattern.compile(regxp);
		Matcher matcher = pattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		boolean result1 = matcher.find();
		while (result1) {
			matcher.appendReplacement(sb, "");
			result1 = matcher.find();
		}
		matcher.appendTail(sb);
		return sb.toString();
	}

	@Override
	public void onClick(View v) {

		try {
			// String id = null;
			// switch (v.getId()) {
			// case R.id.iv_1:
			// id = recommends.get(0).getPid();
			// break;
			// case R.id.iv_2:
			// id = recommends.get(1).getPid();
			// break;
			// case R.id.iv_3:
			// id = recommends.get(2).getPid();
			// break;
			// case R.id.iv_4:
			// id = recommends.get(3).getPid();
			// break;
			// }

		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}

	}

	private long firstTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			long secondTime = System.currentTimeMillis();
			if (secondTime - firstTime > 2000) { // 如果两次按键时间间隔大于2秒，则不退出
				Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
				firstTime = secondTime;// 更新firstTime
				return true;
			} else { // 两次按键小于2秒时，退出应用
				System.exit(0);
			}
		}
		return super.onKeyDown(keyCode, event);
	}
}
